package com.ruoyi.system.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.uuid.UUID;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.concurrent.ThreadLocalRandom;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {

        LoginUser loginUser = SecurityUtils.getLoginUser();

        //设置创建人
        this.strictInsertFill(metaObject, "createBy", String.class, loginUser.getUsername());

        //设置创建人 id
        this.strictInsertFill(metaObject, "createById", Long.class, loginUser.getUser().getUserId());

        // 设置创建时间
        this.strictInsertFill(metaObject, "createDate", String.class, DateUtils.nowDateToString());
//        String substring = generateUUID().toString().substring(10);
//        this.strictInsertFill(metaObject, "wdcId", String.class,substring);
//        this.strictInsertFill(metaObject, "wdcId", String.class, generateUUID().toString());
//        // 获取ID字段的值
//        Object id = getFieldValByName("wdcId", metaObject);
//        // 如果ID为null，生成UUID
//        if (id == null) {
//            setFieldValByName("wdcId", generateUUID(), metaObject);
//        }
    }

    private Object generateUUID() {

        ThreadLocalRandom random = ThreadLocalRandom.current();
        return new UUID(random.nextLong(), random.nextLong()).toString().replace("-", "");
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //设置更新人
        this.strictUpdateFill(metaObject, "updateById", Long.class, loginUser.getUser().getUserId());
        //设置更新人id
        this.strictUpdateFill(metaObject, "updateBy", String.class, loginUser.getUsername());
        // 设置更新时间
        this.strictUpdateFill(metaObject, "updateDate", String.class, DateUtils.nowDateToString());
    }
}
